package io.renren.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import io.renren.common.exception.ErrorCode;
import io.renren.common.redis.RedisUtils;
import io.renren.common.utils.Result;
import io.renren.modules.sp.dto.SpUserDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@Component
public class MyInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisUtils redisUtils;

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated met
		//返回视图后
		UserContext.clear();
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		//处理后，返回视图前
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		response.setHeader("Access-Control-Allow-Headers", "Content-Type, Token, tokenId");
		String strServletPath = request.getServletPath();
		System.out.println(new Date() + "==============strServletPath====================:"+strServletPath);
		if(-1 != request.getRequestURI().indexOf("/fii/front/user")
				||-1 != request.getRequestURI().indexOf("/fii/front/index")){
				return true;
		}
		if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
			return true;
		}

		//需要放行的URL
		if (  -1 != request.getRequestURI().indexOf("/front/spuser")
				|| -1 != request.getRequestURI().indexOf("/front/user/loginout")
				|| -1 != request.getRequestURI().indexOf("/front/account/register")
				|| -1 != request.getRequestURI().indexOf("/front/upload")
				|| -1 != request.getRequestURI().indexOf("/front/download")
				|| -1 != request.getRequestURI().indexOf("/front/fast/sys/areaDict/list")
				|| -1 != request.getRequestURI().indexOf("/front/index")
				|| -1 != request.getRequestURI().indexOf("/front/spuser/queryCertificateBy")
				|| -1 != request.getRequestURI().indexOf("/front/spuser/t/")
				|| -1 != request.getRequestURI().indexOf("/front/spuser/tr/")
				|| -1 != request.getRequestURI().indexOf("/front/spuser/updateUserType")
				|| -1 != request.getRequestURI().indexOf("/front/spuser/queryUserByTeamUserId")
				|| -1 != request.getRequestURI().indexOf("/front/spuser/saveScore")
		) {
			return true;
		}

		String token = getToken(request);
		String key ="USER:"+token;
		System.out.println("key:"+key);
		Object userInfo =redisUtils.get(key);
		 if(userInfo==null){
			 Result result = new Result();
			 result.error(ErrorCode.UNAUTHORIZED);
			 result.setMsg("登录失效，请重新登录");
			 String json = new Gson().toJson(result);
			 response.setContentType("application/json;charset=UTF-8");
			 response.getWriter().print(json);
			 //request.getRequestDispatcher("/fii/front/user/needLogin").forward(request,response);
			 return false;
			 //token失效
		 	//设置未登录
			// response.setStatus(401);
			//return false;
			//return true;
		}else {
			 SpUserDTO user = JSONObject.parseObject((String) userInfo, SpUserDTO.class);
			 UserContext.put(user);
			 //增加过期时间
			 redisUtils.expire(key, 3600L);
			 String tokenKey = "TOKEN:" + user.getAccount();
			 System.out.println("tokenKey:"+tokenKey);
			 String currentToken = (String)redisUtils.get(tokenKey);
			 if(!token.equals(currentToken)){
				 /*response.setStatus(401);
				 Map<Object, Object> map = new HashMap<>();
				 map.put("success",false);
				 map.put("message","登录过期，请重新登录！");
				 String jsonMap = new ObjectMapper().writeValueAsString(map);
				 response.setContentType("application/json;charset=UTF-8");
				 response.getWriter().println(jsonMap);*/
				 Result result = new Result();
				 result.error(ErrorCode.UNAUTHORIZED);
				 result.setMsg("登录失效，请重新登录");
				 String json = new Gson().toJson(result);
				 response.setContentType("application/json;charset=UTF-8");
				 response.getWriter().print(json);
				 return false;
			 }
			 //增加过期时间
			 redisUtils.expire(tokenKey, 3600L);

		 }
		//请求处理请
		return true;
	}

	private String getToken(HttpServletRequest request) {
		;
		Enumeration<String> a = request.getHeaderNames();
		while(a.hasMoreElements()){
			String key = a.nextElement();
					System.out.println(key+":"+request.getHeader(key));
		}
		String token = request.getHeader("tokenid");
		if(StringUtils.isBlank(token)){
			token =request.getParameter("tokenid");
		}
		return token;
	}

}
